﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace System.Json
{
    public class Convert
    {
        public static String SerializeObject(Object obj)
        {
            //return JsonConvert.SerializeObject(obj);
            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());

            string szJson = "";

            //序列化

            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, obj);
                szJson = Encoding.UTF8.GetString(stream.ToArray(), 0, stream.ToArray().Length);
            }
            return szJson;
        }

        public static Object DeserializeObject(String json, Type t)
        {
            //return JsonConvert.DeserializeObject(json, t);
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {

                DataContractJsonSerializer serializer = new DataContractJsonSerializer(t);

                return serializer.ReadObject(ms);

            }
        }
    }
}
